package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.dao.PaymentDAO;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class PaymentController {

    @Autowired
    private PaymentDAO paymentDAO;

    @Autowired
    private DiscoveryClient discoveryClient;

    /*获得配置文件中的端口号*/
    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/payment/get/{id}")
    public CommonResult get(@PathVariable int id){
        Payment payment=paymentDAO.selectByPrimaryKey(id);
        if (payment==null){
            return new CommonResult(444,"没有该id的相关数据,serverPort:"+serverPort);
        }else {
            return new CommonResult(200,"success,serverPort:"+serverPort,payment);
        }
    }

    @PostMapping("/payment/insert")
    public CommonResult get(@RequestBody Payment payment){
        int res=paymentDAO.insert(payment);
        if (res <= 0){
            return new CommonResult(444,"插入数据失败,serverPort:"+serverPort);
        }else {
            return new CommonResult(200,"success,serverPort:"+serverPort,payment);
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services=discoveryClient.getServices();
        for (String service : services) {
            log.info("注册中心内的服务有:"+service);
        }
        /*获取服务下对应的实例
        * 单机只有一个实例
        * 如果是集群，会有多个实例
        * */
        List<ServiceInstance> instances=discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("serviceName:"+instance.getServiceId());
            log.info("instanceIP:"+instance.getHost());
            log.info("instancePort:"+instance.getPort());
            log.info("instanceUrl:"+instance.getUri());
            log.info("========================");
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping(value = "/payment/getTimeOut")
    public String getTimeOut() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return serverPort;
    }

}
